<template>
  <el-dialog
    v-model="dialogVisible"
    :title="note?.title || t('favorites.notes.detail')"
    width="90%"
    top="5vh"
    :before-close="handleClose"
    class="note-view-dialog"
  >
    <div class="note-view-container">
      <!-- 便签头部信息 -->
      <div class="note-header">
        <div class="note-meta">
          <div class="meta-item">
            <el-icon><Document /></el-icon>
            <span>{{ t('favorites.notes.createdAt') }}{{ formatDate(note?.createdAt) }}</span>
          </div>
          <div class="meta-item" v-if="note?.updatedAt !== note?.createdAt">
            <el-icon><Edit /></el-icon>
            <span>{{ t('favorites.notes.updatedAt') }}{{ formatDate(note?.updatedAt) }}</span>
          </div>
          <div class="meta-item" v-if="note?.folder">
            <el-icon><Folder /></el-icon>
            <span>{{ t('favorites.notes.folderLabel') }}{{ note.folder.name }}</span>
          </div>
        </div>
        <div class="note-actions">
          <el-button
            type="primary"
            :icon="Edit"
            @click="handleEdit"
          >
            {{ t('favorites.notes.editNote') }}
          </el-button>
          <el-button
            type="info"
            :icon="Download"
            @click="handleExport"
            :loading="exporting"
          >
            {{ t('favorites.notes.exportMarkdown') }}
          </el-button>
          <el-button
            :type="note?.isFavorite ? 'warning' : 'success'"
            :icon="Star"
            @click="handleToggleFavorite"
          >
            {{ note?.isFavorite ? t('favorites.notes.unfavorite') : t('favorites.notes.favorite') }}
          </el-button>
        </div>
      </div>

      <!-- 便签标签 -->
      <div class="note-tags" v-if="note?.tags?.length">
        <el-tag 
          v-for="tag in note.tags" 
          :key="tag.id"
          :type="getTagType(tag.color)"
          size="small"
          style="margin-right: 8px;"
        >
          {{ tag.name }}
        </el-tag>
      </div>

      <!-- 便签内容 -->
      <div class="note-content">
        <div class="content-tabs">
          <el-tabs v-model="activeTab" type="border-card">
            <el-tab-pane :label="t('favorites.notes.renderedView')" name="rendered">
              <div class="markdown-content">
                <MdPreview
                  :id="`note-view-${note?.id || 'preview'}`"
                  :modelValue="note?.markdownContent || note?.content || ''"
                  :theme="previewTheme"
                  language="zh-CN"
                />
              </div>
            </el-tab-pane>
            <el-tab-pane :label="t('favorites.notes.sourceView')" name="raw">
              <div class="raw-content">
                <pre>{{ note?.content || note?.markdownContent }}</pre>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>

      <!-- 提醒信息 -->
      <div class="note-reminder" v-if="note?.reminderTime">
        <el-alert
          :title="`${t('favorites.notes.reminderTime')}${formatDate(note.reminderTime)}`"
          type="info"
          :icon="Bell"
          :closable="false"
        />
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">{{ t('favorites.dialogs.close') }}</el-button>
        <el-button type="primary" :icon="Edit" @click="handleEdit">
          {{ t('favorites.notes.editNote') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { Document, Edit, Folder, Star, Bell, Download } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { noteApi } from '@/api/note'
import { MdPreview } from 'md-editor-v3'
import 'md-editor-v3/lib/preview.css'

// Props
interface Props {
  visible: boolean
  note?: any
}

const props = defineProps<Props>()

// 国际化
const { t } = useI18n()

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'edit': [note: any]
  'toggle-favorite': [note: any]
}>()

// 响应式数据
const activeTab = ref('rendered')
const exporting = ref(false)

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value: boolean) => emit('update:visible', value)
})

// Markdown 预览主题
const previewTheme = computed(() => {
  return document.documentElement.classList.contains('dark') ? 'dark' : 'light'
})

// 方法
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

const getTagType = (color: string) => {
  const colorMap: { [key: string]: string } = {
    '#F56C6C': 'danger',
    '#E6A23C': 'warning', 
    '#67C23A': 'success',
    '#409EFF': 'primary',
    '#909399': 'info'
  }
  return colorMap[color] || ''
}

const handleClose = () => {
  emit('update:visible', false)
}

const handleEdit = () => {
  emit('edit', props.note)
  handleClose()
}

const handleToggleFavorite = () => {
  emit('toggle-favorite', props.note)
}

const handleExport = async () => {
  if (!props.note?.id) {
    ElMessage.error('便签信息不完整')
    return
  }

  try {
    exporting.value = true

    console.log('开始导出便签:', props.note.id)

    // 使用fetch API直接请求
    const token = localStorage.getItem('token')
    const response = await fetch(`/api/notes/${props.note.id}/export/markdown`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })

    console.log('Fetch响应状态:', response.status)
    console.log('Fetch响应头:', response.headers)

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }

    // 获取响应文本
    const markdownContent = await response.text()
    console.log('获取到内容长度:', markdownContent.length)

    if (!markdownContent) {
      throw new Error('导出内容为空')
    }

    // 创建下载链接
    const blob = new Blob([markdownContent], { type: 'text/markdown;charset=utf-8' })
    const url = window.URL.createObjectURL(blob)

    // 生成文件名
    const fileName = `${props.note.title || t('favorites.notes.title')}_${new Date().toISOString().slice(0, 10)}.md`

    console.log('准备下载文件:', fileName)

    // 创建下载链接并触发下载
    const link = document.createElement('a')
    link.href = url
    link.download = fileName
    document.body.appendChild(link)
    link.click()

    // 清理
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success(t('favorites.notes.exportSuccess'))

  } catch (error: any) {
    console.error('导出便签失败:', error)
    ElMessage.error(t('favorites.notes.exportFailed') + ': ' + (error.message || t('favorites.notes.unknownError')))
  } finally {
    exporting.value = false
  }
}

// 监听便签变化，重置标签页
watch(() => props.note, () => {
  activeTab.value = 'rendered'
})
</script>

<style scoped>
.note-view-dialog {
  --el-dialog-padding-primary: 20px;
}

/* 对话框深度样式 */
.note-view-dialog :deep(.el-dialog) {
  margin: 5vh auto;
  max-height: 90vh;
  height: 90vh;
  display: flex;
  flex-direction: column;
}

.note-view-dialog :deep(.el-dialog__header) {
  flex-shrink: 0;
}

.note-view-dialog :deep(.el-dialog__body) {
  flex: 1;
  padding: 20px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.note-view-dialog :deep(.el-dialog__footer) {
  flex-shrink: 0;
}

.note-view-container {
  height: 70vh;
  max-height: 70vh;
  display: flex;
  flex-direction: column;
  gap: 20px;
  overflow: hidden;
}

.note-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.note-meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.note-actions {
  display: flex;
  gap: 12px;
}

.note-tags {
  padding: 12px 0;
}

.note-content {
  flex: 1;
  overflow: auto;
  min-height: 0; /* 确保flex子元素可以收缩 */
  display: flex;
  flex-direction: column;
}

.content-tabs {
  height: 100%;
  flex: 1;
}

.content-tabs :deep(.el-tabs__header) {
  margin-bottom: 16px;
}

.content-tabs :deep(.el-tabs__content) {
  height: calc(100% - 50px);
  overflow: hidden;
  padding: 0;
}

.content-tabs :deep(.el-tab-pane) {
  height: 100%;
  max-height: 100%;
  overflow-y: scroll !important;
  overflow-x: hidden;
  padding: 0;
  box-sizing: border-box;
  position: relative;
}

.markdown-content {
  padding: 20px;
  line-height: 1.6;
  font-size: 16px;
  color: var(--el-text-color-primary);
  height: 100%;
  min-height: 100%;
  box-sizing: border-box;
  overflow: visible; /* 让父容器处理滚动 */
}

.markdown-content :deep(h1) {
  font-size: 24px;
  margin: 20px 0 16px;
  color: var(--el-text-color-primary);
  border-bottom: 2px solid var(--el-border-color);
  padding-bottom: 8px;
}

.markdown-content :deep(h2) {
  font-size: 20px;
  margin: 16px 0 12px;
  color: var(--el-text-color-primary);
  border-bottom: 1px solid var(--el-border-color-lighter);
  padding-bottom: 6px;
}

.markdown-content :deep(h3) {
  font-size: 18px;
  margin: 12px 0 8px;
  color: var(--el-text-color-primary);
}

.markdown-content :deep(p) {
  margin: 12px 0;
  line-height: 1.7;
}

.markdown-content :deep(ul) {
  margin: 12px 0;
  padding-left: 24px;
}

.markdown-content :deep(li) {
  margin: 6px 0;
  line-height: 1.6;
}

.markdown-content :deep(pre) {
  background: var(--el-fill-color-light);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 6px;
  padding: 16px;
  margin: 16px 0;
  overflow-x: auto;
}

.markdown-content :deep(a) {
  color: var(--el-color-primary);
  text-decoration: none;
}

.markdown-content :deep(a):hover {
  text-decoration: underline;
}

.markdown-content :deep(strong) {
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.markdown-content :deep(em) {
  font-style: italic;
  color: var(--el-text-color-regular);
}

.markdown-content :deep(code) {
  background: var(--el-fill-color-light);
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 14px;
}

.markdown-content :deep(pre code) {
  background: none;
  padding: 0;
  border-radius: 0;
}

.raw-content {
  height: 100%;
  min-height: 100%;
  overflow: visible; /* 让父容器处理滚动 */
  background: var(--el-fill-color-lighter);
  border-radius: 6px;
  box-sizing: border-box;
}

.raw-content pre {
  margin: 0;
  padding: 20px;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.5;
  color: var(--el-text-color-primary);
  background: transparent;
  height: auto;
  min-height: 100%;
}

/* 强制滚动样式 - 直接针对Tab面板 */
.note-view-dialog :deep(.el-tab-pane) {
  overflow-y: scroll !important;
  overflow-x: hidden !important;
  max-height: 100% !important;
  scrollbar-width: thin;
  scrollbar-color: var(--el-color-primary) var(--el-fill-color-light);
}

/* Tab面板滚动条样式 */
.note-view-dialog :deep(.el-tab-pane)::-webkit-scrollbar {
  width: 8px;
}

.note-view-dialog :deep(.el-tab-pane)::-webkit-scrollbar-track {
  background: var(--el-fill-color-light);
  border-radius: 4px;
}

.note-view-dialog :deep(.el-tab-pane)::-webkit-scrollbar-thumb {
  background: var(--el-color-primary);
  border-radius: 4px;
}

.note-view-dialog :deep(.el-tab-pane)::-webkit-scrollbar-thumb:hover {
  background: var(--el-color-primary-dark-2);
}

.note-reminder {
  margin-top: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
